﻿using Avalon.Core.Data;
using Avalon.Core.Providers;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Avalon.Core.MVC.Helpers
{
    public class ReferencedCollection : ICollection<IEntity>
    {
        private List<IEntity> _collection;

        public IEntity Parent { get; set; }
        public bool AllowAdd { get; set; }
        public bool AllowDelete { get; set; }
        public bool AllowEdit { get; set; }

        public Type CollectionType { get; set; }

        public ReferencedCollection()
        {
            _collection = new List<IEntity>();
        }

        public ReferencedCollection(IEnumerable<IEntity> collection) : this()
        {
            if (collection == null) throw new Exception("Collection cannot be null.");
            CollectionType = collection.GetType().GetGenericArguments()[0];
            _collection = new List<IEntity>(collection);
        }

        public ModelMetadata CreateModelMetadata() {
            return ModelMetadataProviders.Current.GetMetadataForType(null, CollectionType);
        }

        public void Add(IEntity item)
        {
            _collection.Add(item);
        }

        public void Clear()
        {
            _collection.Clear();
        }

        public bool Contains(IEntity item)
        {
            return _collection.Contains(item);
        }

        public void CopyTo(IEntity[] array, int arrayIndex)
        {
            _collection.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _collection.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(IEntity item)
        {
            return _collection.Remove(item);
        }

        public IEnumerator<IEntity> GetEnumerator()
        {
            return _collection.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _collection.GetEnumerator();
        }
    }
}
